273. Integer to English Words
1. Question
Convert a non-negative integer num
to its English words representation.
2. Examples
Example 1:
Input: num = 123
Output: "One Hundred Twenty Three"
Example 2:
Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: num = 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
3. Constraints
- 0 <= num <= 231 - 1
4. References
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/integer-to-english-words 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
5. Solutions
百单位需要额外注意,每三个数为一个大单位。所以可以剥离成一个单独的函数。
遍历模拟即可。
class Solution {
static String[] small = {
"Zero", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
static String[] medium = {
"", "", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"
};
static String[] large = {
"", "Thousand", "Million", "Billion"
};
private StringBuilder num2Str(int x) {
StringBuilder sb = new StringBuilder();
if (x >= 100) {
sb.append(small[x / 100]).append(" Hundred").append(" ");
x %= 100;
}
if(x >= 20) {
sb.append(medium[x / 10]).append(" ");
x %= 10;
}
if (x != 0) {
sb.append(small[x]).append(" ");
}
return sb;
}
public String numberToWords(int num) {
if (num == 0) {
return small[num];
}
StringBuffer sb = new StringBuffer();
int count = 0;
while (num != 0) {
int k = num % 1000;
if (k != 0) {
StringBuilder s = num2Str(k);
s.append(large[count]).append(" ");
sb.insert(0, s);
}
count++;
num /= 1000;
}
return sb.toString().trim();
}
}